import Vue from 'vue';

const isPromise = function (promise) {
  return promise && typeof promise.then === 'function' && typeof promise.catch === 'function';
};

const errorHandler = (error, vm, info) => {
  console.error('\n出现错误：', error, '\n出错组件：', vm, '\n错误信息：', info);
};

const registerActionHandle = function (actions) {
  Object.keys(actions).forEach((key) => {
    const fn = actions[key];
    actions[key] = function (...args) {
      const promise = fn.apply(this, args);
      if (isPromise(promise)) {
        return promise.catch(errorHandler);
      } else {
        return promise;
      }
    };
  });
};

const registerVuex = (instance) => {
  if (instance.$options['store']) {
    let actions = instance.$options['store']['_actions'] || {};
    if (actions) {
      let tempActions = {};
      Object.keys(actions).forEach((key) => {
        tempActions[key] = actions[key][0];
      });
      registerActionHandle(tempActions);
    }
  }
};

const registerVue = (instance) => {
  if (instance.$options.methods) {
    const actions = instance.$options.methods || {};
    if (actions) {
      registerActionHandle(actions);
    }
  }
};

const errorPlugin = {
  install: (Vue, options) => {
    Vue.config.errorHandler = errorHandler;
    Vue.mixin({
      beforeCreate() {
        registerVue(this);
        registerVuex(this);
      },
    });
    Vue.prototype.$throw = errorHandler;
  },
};

Vue.use(errorPlugin);
